package com.zoncont.common.utils;

import com.zoncont.common.constant.RequestHeaderConstants;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.net.URLDecoder;
import java.util.Date;


/**
 * 实体类相关工具类 解决问题： 1、快速对实体的常驻字段，如：createUser、createHost、upddateUser等值快速注入
 *
 * @author zoncont.ahanu
 */
public class EntityUtils {
    /**
     * 快速将bean的updateTime, updateName, updateBy, createTime, createName, createBy附上相关值
     *
     * @param entity 实体bean
     */
    public static <T> void setCreatAndUpdatInfo(T entity) {
        setCreateInfo(entity);
        setUpdatedInfo(entity);
    }

    /**
     * 快速将bean的createName、createBy、createTime附上相关值
     *
     * @param entity 实体bean
     */
    public static <T> void setCreateInfo(T entity) {
        // 默认属性
        String[] fields = {"createName", "createBy", "createTime"};
        String timeFiled = "createTime";

        setDefaultVaues(entity, fields, timeFiled);
    }

    private static <T> void setDefaultVaues(T entity, String[] fields, String timeFiled) {
        String name = "";
        String id = "";
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            if (request != null) {
                if (StringUtils.isNotBlank(request.getHeader(RequestHeaderConstants.CURRENT_USER_NAME))) {
                    name = String.valueOf(request.getHeader(RequestHeaderConstants.CURRENT_USER_NAME));
                    try {
                        name = URLDecoder.decode(name, "utf8");
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
                if (StringUtils.isNotBlank(request.getHeader(RequestHeaderConstants.CURRENT_USER_ID))){
                    id = String.valueOf(request.getHeader(RequestHeaderConstants.CURRENT_USER_ID));
                }
            }
        }
        Field field = ReflectionUtils.getAccessibleField(entity, timeFiled);
        // 默认值
        Object[] value = null;
        if (field != null && field.getType().equals(Date.class)) {
            value = new Object[]{name, id, new Date()};
        }

        // 填充默认属性值
        setDefaultValues(entity, fields, value);
    }

    /**
     * 快速将bean的upddateUser、updateHost、updateTime附上相关值
     *
     * @param entity 实体bean
     */
    public static <T> void setUpdatedInfo(T entity) {
        // 默认属性
        String[] fields = {"updateName", "updateUser", "updateHost", "modifiedTime"};

        String timeFiled = "modifiedTime";

        setDefaultVaues(entity, fields, timeFiled);
    }

    /**
     * 依据对象的属性数组和值数组对对象的属性进行赋值
     *
     * @param entity 对象
     * @param fields 属性数组
     * @param value  值数组
     */
    private static <T> void setDefaultValues(T entity, String[] fields, Object[] value) {
        for (int i = 0; i < fields.length; i++) {
            String field = fields[i];
            if (ReflectionUtils.hasField(entity, field) && value[i] != null) {
                ReflectionUtils.invokeSetter(entity, field, value[i]);
            }
        }
    }

    /**
     * 根据主键属性，判断主键是否值为空
     *
     * @return 主键为空，则返回false；主键有值，返回true
     */
    public static <T> boolean isPKNotNull(T entity, String field) {
        if (!ReflectionUtils.hasField(entity, field)) {
            return false;
        }
        Object value = ReflectionUtils.getFieldValue(entity, field);
        return value != null && !"".equals(value);
    }
}
